package com.xx.pmis.web.actions;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.xx.pmis.model.Account;
import com.xx.pmis.model.Card;
import com.xx.pmis.model.Subject;
import com.xx.pmis.services.AccountService;
import com.xx.pmis.services.CardService;
import com.xx.pmis.services.SubjectService;
import com.xx.pmis.web.forms.AccountForm;
import com.xx.pmis.web.util.AccountUtil;
import com.xx.pmis.web.util.CalculateBalance;
import com.xx.pmis.web.util.CurrentDate;
import com.xx.pmis.web.util.DynamicAccountTree;

/**
 * @class 记账本Action类 <br>
 * 
 * @editor 石星星 @Date 2011-9-21 下午03:17:42 <br>
 * @version jdk_1.5.0
 */
public class AccountAction extends PMISBaseAction {
	private static final Log log = LogFactory.getLog(AccountAction.class);

	SubjectService subjectService = getPMISServices().getSubjectService();
	//SubjectSonService subjectSonService = getPMISServices().getSubjectSonService();
	AccountService accountService = getPMISServices().getAccountService();
	CardService cardService = getPMISServices().getCardService();

	DynamicAccountTree dynamicAccountTree = new DynamicAccountTree();
	AccountUtil accountUtil = new AccountUtil();
	CalculateBalance calculateBalance = new CalculateBalance();

	// 查询所有记账本
	public ActionForward listAccount(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		List<Account> accountList = null;
		try {
			accountList = accountService.getAllAccountByCondition(" order by postDate desc");
		} catch (Exception e) {
			log.info("【财务管理/记账本】查询记账异常！" + e.toString());
		}
		List<?> accountTreeList = dynamicAccountTree.MadeAccountTree();
		try {
			Number count = accountService.getCountOfAccountByCondition("");
			// 记账数目，查询系统中共有多少条记账
			request.setAttribute("count", String.valueOf(count));
		} catch (Exception e) {
			log.info("【财务管理/记账本】查询账目数目异常！" + e.toString());
		}
		// 记账本树
		request.getSession(true).setAttribute("accountTreeList", accountTreeList);
		request.setAttribute("accountList", accountList);
		return mapping.findForward("listAccount");
	}

	// 新增
	public ActionForward addAccount(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String subCode = request.getParameter("subCode"); // 收入、支出
		log.info("从页面获得的科目名称为：" + subCode);
		Subject subject = null;
		try {
			subject = subjectService.getSubjectBySubjectID(subCode);
		} catch (Exception e) {
			log.info("【财务管理/记账本/新增】根据科目名称查询科目异常！" + e.toString());
		}
		List<Subject> subjectList = null;
		try {
			subjectList = subjectService.getAllSubjectByCondition(" where subParentID = '" + subject.getSubID() + "'");
		} catch (Exception e) {
			log.info("【财务管理/记账本/新增】根据科目ID查询科目下所有二级科目异常！" + e.toString());
		}
		if (subject.getSubCode().equals("002") || subject.getSubCode().equals("004")) {
			request.setAttribute("income", false);
			request.setAttribute("output", true);

		} else if (subject.getSubCode().equals("003") || subject.getSubCode().equals("005")) {
			request.setAttribute("income", true);
			request.setAttribute("output", false);
		} else {
			log.info(subject.getSubName() + "该科目暂不记账！");
		}
		// 记账日期
		request.setAttribute("accountDate", CurrentDate.currentDate());
		request.setAttribute("subName", subject.getSubName());
		request.setAttribute("subjectList", subjectList);
		request.setAttribute("position", "记账本/新增");
		return mapping.findForward("addAccount");
	}

	// 新增，处理方法
	public ActionForward addAccount_Do(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		AccountForm f = (AccountForm) form;
		String accountDate = f.getAccountDate(); // 记账日期
		String subjectID = f.getSubjectID(); // 科目ID
		String reduction = f.getReduction(); // 减少
		String increase = f.getIncrease(); // 增加
		String accountDesc = f.getAccountDesc(); // 描述

		double balance = 0.00; // 计算余额

		Account account = new Account();
		account.setAccountDate(accountDate);
		account.setSubjectID(subjectID);

		Subject subject = null;
		try {
			subject = subjectService.getSubjectBySubjectID(subjectID);
		} catch (Exception e) {
			log.info("【财务管理/记账本/新增】根据科目ID查询该科目异常！" + e.toString());
		}
		// 支出/水电费
		if (subject.getSubParentID().equals("002") || subject.getSubParentID().equals("004")) {// 收入
			account.setReduction("");
			account.setIncrease(increase + "￥");
		} else if (subject.getSubParentID().equals("003") || subject.getSubParentID().equals("005")) {// 支出
			account.setReduction("-" + reduction + "￥");
			account.setIncrease("");
		} else {
			log.info(subject.getSubName() + "该科目暂不记录记账本！");
		}
		log.info("记账日期：" + accountDate + "，科目：" + subject.getSubName() + "/" + subject.getSubCode()
				+ "，支出：" + reduction + "元，收入：" + increase + "元。");
		// 暂且用这种笨方法计算余额，存在不准确风险
		List<Account> accountList = null;
		try {
			accountList = accountService.getAllAccountByCondition(" order by postDate desc");
		} catch (Exception e) {
			log.info("【财务管理/记账本/新增】查询所有记账异常！" + e.toString());
		}
		if (accountList.size() == 0) {
			balance = 0.00;
			log.info("余额：" + balance + "元。");
		} else {
			Account accountBalance = (Account) accountList.get(0);
			log.info("描述：" + accountBalance.getAccountDesc() + "，余额：" + accountBalance.getBalance() + "元。");
			balance = Double.parseDouble(accountBalance.getBalance());
		}
		log.info("记账前余额：" + balance + "元。");
		// 加收入，减支出
		balance = balance + Double.parseDouble(increase) + Double.parseDouble("-" + reduction);
		// 余额
		account.setBalance(accountUtil.if1ZeroTo2Zero(new DecimalFormat("####.##").format(balance)));
		account.setAccountDesc(accountDesc);
		// 凭证编号
		account.setAccountCode(accountUtil.getMaxAccountCode());
		// ID和凭证编号一致
		account.setAccountID(accountUtil.getMaxAccountCode());
		// 制单日期
		account.setPostDate(CurrentDate.currentDateAndTime());
		try {
			accountService.saveOrUpdateAccount(account);
		} catch (Exception e) {
			log.info("【财务管理/记账本/新增】保存记账本异常！" + e.toString());
		}

		this.listAccountByPage(mapping, form, request, response);
		return mapping.findForward("listAccount");
	}

	// 根据二级科目查询所有记账,一级不需要查询
	public ActionForward listAccountBySubjectID(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String subjectID = request.getParameter("subjectID"); // 科目ID
		int PAGESIZE = 20;// 每页记录数
		int totalPage = 1;// 总页数

		// 查询总用户记录数
		int count = 0;
		try {
			count = accountService.getCountOfAccountByCondition(" where subjectID='" + subjectID
					+ "' order by postDate desc");
		} catch (Exception e) {
			log.info("【财务管理/记账本】查询记账数目异常！" + e.toString());
		}
		request.setAttribute("count", count);
		if (count % PAGESIZE == 0) {
			totalPage = count / PAGESIZE;
		} else {
			totalPage = count / PAGESIZE + 1;
		}
		request.setAttribute("totalPage", totalPage);
		// 声明要翻的页
		String pageNum = "1";
		try {
			String thisPageNum = request.getParameter("pageNum");
			// 如果传了页码参数
			if (thisPageNum != null && thisPageNum.length() != 0) {
				pageNum = thisPageNum;
			}
		} catch (RuntimeException e) {
			log.info("" + e.toString());
		}
		log.info("page:" + pageNum);
		request.setAttribute("pageNum", pageNum);
		List<Account> accountList = null;
		try {
			accountList = accountService.getAllAccountByConditionByPage(" where subjectID='" + subjectID
					+ "' order by postDate desc", Integer.parseInt(pageNum), PAGESIZE);
		} catch (Exception e) {
			log.info("【财务管理/记账本】查询记账记录异常！" + e.toString());
		}
		// 转换accountTransfer数据
		List<Account> accountListTemp = new ArrayList<Account>();
		for (Account account : accountList) {
			// 二级科目
			Subject subject = new Subject();
			try {
				subject = subjectService.getSubjectBySubjectID(subjectID);
			} catch (Exception e) {
				log.info("【财务管理/记账本】根据二级科目ID查询该二级科目！" + e.toString());
			}
			// 父科目
			Subject subjectParent = new Subject();
			try {
				subjectParent = subjectService.getSubjectBySubjectID(subject.getSubParentID());
			} catch (Exception e) {
				log.info("【财务管理/记账本】根据二级科目的父科目ID查询该父科目！" + e.toString());
			}
			// 一级科目名称
			account.setTransferAccount(subjectParent.getSubName() + "/" + subject.getSubName() + subjectID);
			accountListTemp.add(account);
		}

		List<?> accountTreeList = dynamicAccountTree.MadeAccountTree();
		// 记账本树
		request.getSession(true).setAttribute("accountTreeList", accountTreeList);
		request.setAttribute("accountList", accountListTemp);
		request.setAttribute("PAGESIZE", PAGESIZE);
		// 如果要翻的这页是第一页
		if ("1".equals(pageNum)) {
			// 设置noUp为yes(界面上用此控制'首页'与'上一页'按钮失效)
			request.setAttribute("noUp", "yes");
		}

		// 如果要翻的这页是最后页
		if (totalPage == Integer.parseInt(pageNum)) {
			// 设置noDown为yes(界面上用此控制'下一页'与'尾页'按钮失效)
			request.setAttribute("noDown", "yes");
		}

		// 本月上月支出收入
		Map<String, String> map = accountUtil.getMonthReductionAndIncreaseBySsID(subjectID);
		request.setAttribute("currentReduction", map.get("currentReduction"));// 本月支出
		request.setAttribute("currentIncrease", map.get("currentIncrease"));// 本月收入
		request.setAttribute("lastReduction", map.get("lastReduction"));// 上月支出
		request.setAttribute("lastIncrease", map.get("lastIncrease"));// 上月收入
		request.setAttribute("position", "财务管理/记账本");

		// 记账本树
		request.getSession(true).setAttribute("accountTreeList", accountTreeList);
		request.setAttribute("action", "account.do");
		request.setAttribute("subjectID", subjectID);
		request.setAttribute("method", "listAccountBySubjectID");
		return mapping.findForward("listAccount");
	}

	// 分页显示
	public ActionForward listAccountByPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		int PAGESIZE = 20;// 每页记录数
		int totalPage = 1;// 总页数

		// 查询总用户记录数
		int count = 0;
		try {
			count = accountService.getCountOfAccountByCondition("");
		} catch (Exception e) {
			log.info("【财务管理/记账本】查询记账数目异常！" + e.toString());
		}
		request.setAttribute("count", count);
		if (count % PAGESIZE == 0) {
			totalPage = count / PAGESIZE;
		} else {
			totalPage = count / PAGESIZE + 1;
		}
		request.setAttribute("totalPage", totalPage);
		// 声明要翻的页
		String pageNum = "1";
		try {
			String thisPageNum = request.getParameter("pageNum");
			// 如果传了页码参数
			if (thisPageNum != null && thisPageNum.length() != 0) {
				pageNum = thisPageNum;
			}
		} catch (RuntimeException e) {
			log.info("" + e.toString());
		}
		log.info("page:" + pageNum);
		request.setAttribute("pageNum", pageNum);
		List<Account> accountList = null;
		try {
			accountList = accountService.getAllAccountByConditionByPage(" order by postDate desc", Integer
					.parseInt(pageNum), PAGESIZE);
		} catch (Exception e) {
			log.info("【财务管理/记账本】查询记账记录异常！" + e.toString());
		}
		// 转换accountTransfer数据
		List<Account> accountListTemp = new ArrayList<Account>();
		for (Account account : accountList) {
			// 二级科目
			String subjectID = account.getSubjectID();
			Subject subject = new Subject();
			try {
				subject = subjectService.getSubjectBySubjectID(subjectID);
			} catch (Exception e) {
				log.info("【财务管理/记账本】根据二级科目ID查询该二级科目！" + e.toString());
			}
			// 父科目
			Subject subjectParent = new Subject();
			try {
				subjectParent = subjectService.getSubjectBySubjectID(subject.getSubParentID());
			} catch (Exception e) {
				log.info("【财务管理/记账本】根据二级科目的父科目ID查询该父科目！" + e.toString());
			}
			// 一级科目名称
			account.setTransferAccount(subjectParent.getSubName() + "/" + subject.getSubName() + subjectID);
			accountListTemp.add(account);
		}
		List<?> accountTreeList = dynamicAccountTree.MadeAccountTree();
		// 记账本树
		request.getSession(true).setAttribute("accountTreeList", accountTreeList);
		request.setAttribute("accountList", accountListTemp);
		request.setAttribute("PAGESIZE", PAGESIZE);
		// 如果要翻的这页是第一页
		if ("1".equals(pageNum)) {
			// 设置noUp为yes(界面上用此控制'首页'与'上一页'按钮失效)
			request.setAttribute("noUp", "yes");
		}

		// 如果要翻的这页是最后页
		if (totalPage == Integer.parseInt(pageNum)) {
			// 设置noDown为yes(界面上用此控制'下一页'与'尾页'按钮失效)
			request.setAttribute("noDown", "yes");
		}

		Map<String, String> map = accountUtil.getMonthReductionAndIncrease();
		request.setAttribute("currentReduction", map.get("currentReduction"));// 本月支出
		request.setAttribute("currentIncrease", map.get("currentIncrease"));// 本月收入
		request.setAttribute("lastReduction", map.get("lastReduction"));// 上月支出
		request.setAttribute("lastIncrease", map.get("lastIncrease"));// 上月收入
		request.setAttribute("action", "account.do");
		request.setAttribute("position", "财务管理/记账本");
		request.setAttribute("method", "listAccountByPage");
		return mapping.findForward("listAccount");
	}

	// 数据分析，饼图，柱状图
	public ActionForward barChart(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		request.setAttribute("position", "记账本/数据分析");
		return mapping.findForward("datasetAccount");
	}

	// 最近12个月的财务月报
	public ActionForward listReductionAndIncreaseOfTwelveMonths(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		List<Account> all = accountUtil.getReductionAndIncreaseOfTwelveMonths();

		request.setAttribute("accountList", all);
		request.setAttribute("position", "财务管理/财务月报");
		return mapping.findForward("listAccountMonthly");
	}

	// 穿透明细
	public ActionForward listAccountByMonth(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String date = request.getParameter("date");
		List<Account> accountList = accountUtil.getAllAccountByMonth(date);
		// 转换accountTransfer数据
		List<Account> accountListTemp = new ArrayList<Account>();
		for (Account account : accountList) {
			// 二级科目
			String subjectID = account.getSubjectID();
			Subject subject = new Subject();
			try {
				subject = subjectService.getSubjectBySubjectID(subjectID);
			} catch (Exception e) {
				log.info("【财务管理/记账本】根据二级科目ID查询该二级科目！" + e.toString());
			}
			// 父科目
			Subject subjectParent = new Subject();
			try {
				subjectParent = subjectService.getSubjectBySubjectID(subject.getSubParentID());
			} catch (Exception e) {
				log.info("【财务管理/记账本】根据二级科目的父科目ID查询该父科目！" + e.toString());
			}
			if(!account.getAccountID().equals("88888")) {
				account.setTransferAccount(subjectParent.getSubName() + "/" + subject.getSubName() + subjectID);
			}
			accountListTemp.add(account);
		}

		request.setAttribute("accountList", accountListTemp);
		request.setAttribute("position", "财务管理/财务月报/穿透明细");
		return mapping.findForward("listAccountByMonth");
	}

	// 月初对账
	public ActionForward verificationOfAccountByMonthly(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		double totalMoney = 0.00;
		List<Card> all = null;
		try {
			all = cardService.getAllCard();
		} catch (Exception e) {
			log.info("【物资管理/卡片】查询所有卡片异常！" + e.toString());
		}

		List<Card> list = new ArrayList<Card>();
		Card newCard = new Card();
		for (Card card : all) {
			// 计算所以卡片月结和
			totalMoney = totalMoney + Double.parseDouble(card.getBalance());
			list.add(card);
		}
		newCard.setBankName("合计");
		String stringTotalMoney = String.valueOf(new DecimalFormat("####.##").format(totalMoney));
		newCard.setBalance(stringTotalMoney);
		list.add(newCard);

		request.setAttribute("cardList", list);
		// 对账日期
		String currentDate = CurrentDate.currentDate();
		request.setAttribute("currentDate", currentDate);
		// 实际结余
		request.setAttribute("totalMoney", stringTotalMoney);
		// 账本余额，根据最大凭证号求账本余额
		String systemMoney = "";

		systemMoney = accountUtil.getBalanceOfLastOnce();
		request.setAttribute("systemMoney", systemMoney);
		// 差额
		double mistakeMoney = totalMoney - Double.parseDouble(systemMoney);
		String stringMistakeMoney = String.valueOf(new DecimalFormat("####.##").format(mistakeMoney));
		request.setAttribute("mistakeMoney", stringMistakeMoney);
		// 状态
		String state = "";
		String stateMsg = "";
		if (mistakeMoney > 0) {
			state = "少";
			stateMsg = "少记了" + stringMistakeMoney + "￥，平账时选\"收入\"科目。";
		} else if (mistakeMoney < 0 && !stringMistakeMoney.endsWith("-0")) {
			state = "多";
			stateMsg = "多记了" + stringMistakeMoney.replace("-", "") + "￥，平帐时选\"支出\"科目。";

		} else {
			state = "正常";
			stateMsg = "账账相符，暂时不需要对账。";
			request.setAttribute("mistakeMoney", "0");
		}
		request.setAttribute("state", state);
		request.setAttribute("stateMsg", stateMsg);
		request.setAttribute("position", "财务月报/月初对账");
		return mapping.findForward("verificationOfAccount");
	}

	// 平帐
	public ActionForward verificationOfAccountByMonthly_Do(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String mistakeMoney = request.getParameter("mistakeMoney");
		Account account = new Account();
		if (mistakeMoney.startsWith("-")) {
			account.setAccountDate(CurrentDate.currentDate());
			account.setTransferAccount("支出/平帐支出");
			account.setSubjectID("0030020");
			account.setAccountDesc("本月平帐支出");
			account.setReduction(mistakeMoney + "￥");
			account.setIncrease("");
			double balance = calculateBalance.calculateAccountBalance();
			balance = balance + Double.parseDouble(mistakeMoney);
			account.setBalance(String.valueOf(new DecimalFormat("####.##").format(balance)));
		} else {
			account.setAccountDate(CurrentDate.currentDate());
			account.setTransferAccount("收入/平帐收入");
			account.setSubjectID("0020010");
			account.setAccountDesc("本月平帐收入");
			account.setReduction("");
			account.setIncrease(mistakeMoney + "￥");
			double balance = calculateBalance.calculateAccountBalance();
			balance = balance + Double.parseDouble(mistakeMoney);
			account.setBalance(String.valueOf(new DecimalFormat("####.##").format(balance)));
		}
		// 凭证编号
		account.setAccountCode(accountUtil.getMaxAccountCode());
		// 凭证ID
		account.setAccountID(accountUtil.getMaxAccountCode());
		account.setAccountID(accountUtil.getMaxAccountCode());
		// 制单日期
		account.setPostDate(CurrentDate.currentDateAndTime());
		try {
			accountService.saveOrUpdateAccount(account);
		} catch (Exception e) {
			log.info("【财务管理/财务月报/月初对账/平帐】保存记账本异常！" + e.toString());
		}
		request.setAttribute("position", "财务管理/财务月报");
		this.verificationOfAccountByMonthly(mapping, form, request, response);
		return mapping.findForward("verificationOfAccount");
	}

}